/** @file */
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <string>
#include <cstring>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

#include "eximport.h"
#include "filmbaza.h"
#include "defines.h"

const char PRINT_SEPARATOR = ':';

/**
 * @brief filmbaza_import importuje baze filmów do pliku
 * @param fb wskaźnik do bazy danych filmóœ
 * @param file_name nazwa pliku
 * @return 0 jeśli sukces, inaczej kod błędu
 */
int filmbaza_import(filmbaza *fb, std::string file_name)
{	
	std::ifstream ffile;
	std::string line;
	
	if ( !fb ) {
		return -100;
	}

	ffile.open(file_name.c_str());
	if ( !ffile.good() ) {
		PERROR(" ");
		return -errno;
	}
	
	/* clear the list */
	filmbaza_delete_all_films(fb);
	
	std::getline(ffile, line, '\n');
	fb->name = line;
	
	while ( std::getline(ffile, line) ) {
		std::istringstream ffile( line );
		std::string buff;
		film_s info;
		
		if ( !std::getline(ffile, buff, PRINT_SEPARATOR) )
			return -1;
		if ( buff.empty() )
			return -10;
		info.id = atoi(buff.c_str());
		
		
		if ( !std::getline(ffile, buff, PRINT_SEPARATOR) )
			return -2;
		if ( buff.empty() )
			return -10;
		info.name = buff;
		
		if ( !std::getline(ffile, buff, PRINT_SEPARATOR) )
			return -3;
		info.rate = atoi(buff.c_str());
		
		if ( !std::getline(ffile, buff, PRINT_SEPARATOR) )
			return -4;
		info.share.shared = atoi(buff.c_str());
		
		if ( !std::getline(ffile, buff, PRINT_SEPARATOR) )
			return -5;
		info.share.name = buff;
		
		/* nothing more in this line */
		ffile >> buff;
		if ( !buff.compare("\n") )
			return -6;
		
		filmbaza_add(fb, info);
	}
	
	ffile.close();
	return 0;
}
/**
 * @brief filmbaza_export exportuje baze filmów do pliku
 * @param fb wskaźnik do bazy danych filmóœ
 * @param file_name nazwa pliku
 * @return 0 jeśli sukces, inaczej kod błędu
 */
int filmbaza_export(filmbaza *fb, std::string file_name)
{
	std::ofstream ffile;
    film_s **head;
	film_s *film;
	
	if ( !fb ) 
		return -1;

	ffile.open(file_name.c_str());
	if ( !ffile.good() ) {
		perror("");
		return -errno;
	}
	
	
	head = &fb->filmy;
	
	ffile << fb->name << std::endl;
	
    list_for_each(film, head) {
		ffile  << film->id << PRINT_SEPARATOR
			<< film->name << PRINT_SEPARATOR
			<< film->rate << PRINT_SEPARATOR
			<< film->share.shared << PRINT_SEPARATOR
			<< film->share.name << PRINT_SEPARATOR 
			<< std::endl;
	}
	
	ffile.close();
	return 0;
}
